#pragma once
#include <iostream>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"
class InetAddr
{
private:
    void PortNet2Host()
    {
        _port = ::ntohs(_net_addr.sin_port);
    }
    void IpNet2Host(){
        char ipbuffer[64];
        const char *ip = ::inet_ntop(AF_INET, &_net_addr.sin_addr, ipbuffer, sizeof(ipbuffer));
        (void)ip;
        _ip = ip;
    }
public:
    InetAddr(){}
    InetAddr(const struct sockaddr_in &addr)
        : _net_addr(addr)
    {
        PortNet2Host();
        IpNet2Host();
    }
    InetAddr(uint16_t port)
        : _port(port)
        , _ip("")
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = ::htons(_port);
        _net_addr.sin_addr.s_addr = INADDR_ANY;
    }

    struct sockaddr *NetAddr() const
    {
        return CONV(&_net_addr);
    }
    socklen_t NetAddrLen()const{ return sizeof(_net_addr); }

    std::string Ip()const{return _ip;}
    uint16_t Port()const{return _port;}

    std::string Addr() const { return Ip() + ':' + std::to_string(_port); }

    void SetAddr(const sockaddr_in &client, socklen_t &socklen){
        _net_addr = client;
        (void)socklen;

        IpNet2Host();
    }
    // 支持 addr 封装类的比较
    bool operator == (const InetAddr &other_addr) const
    {
        return (_port == other_addr._port) && (_ip == other_addr._ip);
    }

    ~InetAddr(){}

private:
    uint16_t _port;
    sockaddr_in _net_addr;
    std::string _ip;

};